<template>
  <a-upload
    v-model:file-list="fileList"
    list-type="picture-card"
    :before-upload="handleBeforeUpload"
    :customRequest="customUpload"
    @preview="handlePreview"
    :maxCount="1"
    :data="{ biz: props.biz }"
  >
    <div v-if="fileList.length < 1">
      <plus-outlined />
      <div style="margin-top: 8px">上传</div>
    </div>
  </a-upload>

  <!-- 图片预览 -->
  <a-modal
    v-model:visible="previewVisible"
    title="图片预览"
    :footer="null"
  >
    <img alt="预览" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { uploadFileUsingPost } from '@/api/fileController'
import { BIZ_TYPE } from '@/constants/upload'

const props = defineProps<{
  value?: string
  biz: typeof BIZ_TYPE[keyof typeof BIZ_TYPE]
}>()

const emit = defineEmits(['update:value', 'upload-success'])

const fileList = ref<any[]>([])
const previewVisible = ref(false)
const previewImage = ref('')

// 监听value变化，更新fileList
watch(() => props.value, (newVal) => {
  if (newVal) {
    fileList.value = [{
      uid: '-1',
      name: 'image.png',
      status: 'done',
      url: newVal
    }]
  } else {
    fileList.value = []
  }
}, { immediate: true })

// 预览图片
const handlePreview = (file: any) => {
  previewImage.value = file.url || file.preview
  previewVisible.value = true
}

// 上传前校验
const handleBeforeUpload = (file: File) => {
  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  // 验证文件大小（1M）
  const isLt1M = file.size / 1024 / 1024 < 5
  if (!isLt1M) {
    message.error('图片大小不能超过 5MB!')
    return false
  }

  return true
}

// 自定义上传
const customUpload = async ({ file }: any) => {
  try {
    const res = await uploadFileUsingPost(
      { biz: props.biz },
      {},
      file,
      {
        requestType: 'form'  // 确保使用 form 类型
      }
    )

    if (res && res.code === 0) {
      const url = res.data
      fileList.value = [{
        uid: '-1',
        name: file.name,
        status: 'done',
        url
      }]
      emit('update:value', url)
      emit('upload-success', url)
      message.success('上传成功')
    } else {
      message.error(res?.message || '上传失败')
    }
  } catch (error) {
    message.error('上传失败')
  }
}
</script>
